package com.effectiv.gooruda.rest.service.impl;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.ws.rs.core.Response;

import lombok.extern.slf4j.Slf4j;

import net.coobird.thumbnailator.Thumbnails;

import org.imgscalr.Scalr;
import org.springframework.stereotype.Component;

import com.effectiv.gooruda.rest.service.api.ImageService;

@Component
@Slf4j
public class ImageServiceImpl extends ImageService{

	@Override
	public Response convertFormat(String name, 
			String formatToConvert, InputStream inputStream) {
		log.info("Name = {}", name);
		log.info("Inputstream = {}", inputStream);
		log.info("formatToConvert = {}", formatToConvert);
		
		
		return null;
	}

	@Override
	public Response crop(String name, InputStream inputStream, Integer width,
			Integer height, Integer x, Integer y) {
		try {
			BufferedImage originalImage = ImageIO.read(inputStream);
			
			BufferedImage croppedImage = Scalr.crop(originalImage, x, y, width, height, null);
			
		} catch (IOException e) {
			log.error("Error", e);
		}
		return null;
	}

	@Override
	public Response resize(String name, InputStream inputStream, Integer width,
			Integer height) {
		try {
			BufferedImage originalImage = ImageIO.read(inputStream);
			
			BufferedImage resizedImage = Scalr.resize(originalImage, width, height, null);
			
		} catch (IOException e) {
			log.error("Error", e);
		}
		
		return null;
	}

	@Override
	public Response resizeByPercentage(String name, InputStream inputStream,
			Double percentage) {
		try {
			BufferedImage originalImage = ImageIO.read(inputStream);
			
			int targetWidth =  (int) (originalImage.getHeight() * (percentage/100));
			int targetHeight = (int) (originalImage.getWidth() * (percentage/100));
			
			BufferedImage resizedImage = Scalr.resize(originalImage, targetWidth, targetHeight, null);
			
		} catch (IOException e) {
			log.error("Error", e);
		}
		return null;
	}

	

	@Override
	public Response thumbnail(
			String name, 
			InputStream inputStream,
			int width, 
			int height) {
		try {
			BufferedImage originalImage = ImageIO.read(inputStream);
			
			BufferedImage thumbnail = Thumbnails.of(originalImage)
			        .size(width, height)
			        .asBufferedImage();
		} catch (IOException e) {
			log.error("Error", e);
		}
		return null;
	}

	@Override
	public Response thumbnailByPercentage(String name, InputStream inputStream,
			Double percentage) {
		try {
			BufferedImage originalImage = ImageIO.read(inputStream);
			
			BufferedImage thumbnail = Thumbnails.of(originalImage)
					.scale(percentage/100)
			        .asBufferedImage();
		} catch (IOException e) {
			log.error("Error", e);
		}
		return null;
	}

}
